/* 注册提交 */
// 全局路径
var contextPath = "/xhu_rent";
// 登录路径
var login = contextPath + "/login";
// 操作状态码 1-成功，可以进行下一步；0-失败
var userpassCode = 0;
var emailCode = 0;
var passwordCode = 0;

/* 一、用户 注册、登录、发送验证码 相关操作 */
/* 用户注册 */
function submitRegister() {
    // 页面有未完成或错误信息，不能注册
    if(userpassCode == 0 || emailCode == 0 || passwordCode == 0){
        $("#myModalBody").text("请正确填写内容");
        $("#myModal").modal({backdrop:false});
        $("#myModal").modal();
        setTimeout(function () {
            $("#myModal").hide();
        }, 1500);
        return;
    }
    if($("#emailCode").val() == null || $("#emailCode").val() == ''){
        $("#emailCodeCheck").text("（请填写验证码）");
        $("#emailCodeCheck").prop("hidden", "");
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/register",
        async:false,
        data:$("#registerForm").serialize(),
        success:function (data) {
            if(data.code == 200){
                // 注册成功，弹出提示，并转到登录页面
                $("#myModalBody").text("注册成功");
                $("#myModal").modal({backdrop:false});
                $("#myModal").modal();
                setTimeout(function () {
                    $("#myModal").hide();
                    window.location.href= login;
                }, 1000);
            }
        }
    })
}
/* 数据检查 */
function check_email() {
    if($("#email").val() == null || $("#email").val().trim() == ""){
        $("#emailCheck").text("（邮箱不能为空）");
        $("#emailCheck").prop("hidden", "");
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/checkEmail",
        async:false,
        data:{"email": $("#email").val()},
        success:function (data) {
            // 如果数据库中邮箱已存在，则不能注册
            if(data.code == 300){
                $("#emailCheck").prop("hidden", "");
                emailCode = 0;
            }else {
                $("#emailCheck").prop("hidden", "hidden");
                emailCode = 1;
            }
        }
    })
}
/* 检查用户名是否为空 */
function check_username() {
    // 不能为空
    if($("#username").val() == null || $("#username").val().trim() == ""){
        $("#usernameCheck").prop("hidden", "");
        userpassCode = 0;
        return;
    }else {
        $("#usernameCheck").prop("hidden", "hidden");
    }
    // 不能和数据库中同名
    $.ajax({
        type:"POST",
        url: contextPath + "/checkUsername",
        async:false,
        data:{"username": $("#username").val()},
        success:function (data) {
            if(data.code == 200){
                userpassCode = 1;
                $("#usernameCheck").prop("hidden", "hidden");
            }else {
                $("#usernameCheck").text("（用户名已存在，不可重复注册）");
                $("#usernameCheck").prop("hidden", "");
            }
        }
    })
}
/* 密码检查 */
function check_password() {
    var password = $("#password").val();
    var passwordConfirm = $("#passwordConfirm").val();
    if(password.length < 6){
        $("#passwordCheck").prop("hidden", "");
        passwordCode = 0;
        return;
    }else {
        $("#passwordCheck").prop("hidden", "hidden");
    }
    if(password != passwordConfirm){
        $("#passwordConfirmCheck").prop("hidden", "");
        passwordCode = 0;
    }else {
        $("#passwordConfirmCheck").prop("hidden", "hidden");
        passwordCode = 1;
    }
}
/* 错误信息提示 */
function error_clear() {
    $("#emailCodeCheck").prop("hidden", "hidden");
}
/* 发送邮箱验证码 */
function sendEmailCode() {
    var email = $("#email").val();
    $.ajax({
        type:"POST",
        url: contextPath + "/sendEmailCode",
        async:false,
        data:{"email": email},
        success:function (data) {
            $("#emailCodeCheck").text( "（" + data.msg + "）");
            $("#emailCodeCheck").css({"color": "green"});
            $("#emailCodeCheck").prop("hidden", "");
        }
    })
}

/* 找回密码验证邮箱是否已注册，如果注册则发送验证码 */
function sendFindPasswordEmailCode() {
    var email = $("#email").val();
    if(email == ''){
        $("#emailUnExist").text("（请输入邮箱）")
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/checkEmail",
        async:false,
        data:{"email": email},
        success:function (data) {
            if(data.code == 301){   // 邮箱未注册
                $("#emailUnExist").text("（邮箱未注册）");
            }else {
                $("#emailUnExist").text("");
                $.ajax({
                    type:"POST",
                    url: contextPath + "/sendEmailCode",
                    async:false,
                    data:{"email": email},
                    success:function (data) {
                        $("#emailCodeCheck").text( "（" + data.msg + "）");
                        $("#emailCodeCheck").css({"color": "green"});
                    }
                })
            }
        }
    })
}
/* 点击下一步，判断验证码是否正确，显示修改密码输入框 */
function findPassword() {
    var email = $("#email").val();
    var code = $("#emailCode").val();
    if(email == ''){
        $("#emailUnExist").text("（请输入邮箱）")
        return;
    }
    if(code == ''){
        $("#emailCodeCheck").text( "（请输入验证码）");
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/checkEmailCode",
        async:false,
        data:{"email": email, "code": code},
        success:function (data) {
            if(data.code == 201){
                $("#emailCodeCheck").css({"color": "red"});
                $("#emailCodeCheck").text( "（" + data.msg + "）");
            }else {
                $("#emailCodeDiv").prop("hidden", "hidden");
                $("#updatePasswordDiv").prop("hidden", "");
                $("#email").prop("readonly", "readonly");
            }
        }
    })
}
/* 确认修改密码 */
function updateForgotPassword() {
    var email = $("#email").val();
    var password = $("#password").val();
    var confirmPassword = $("#confirmPassword").val();
    if(password.length < 6){
        $("#passwordCheck").text("（密码不能小于6位数）");
        return;
    }
    if(confirmPassword != password){
        $("#confirmPasswordCheck").text("（两次输入密码不相同）");
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/updateForgotPassword",
        async:false,
        data:{"email": email, "password": password},
        success:function (data) {
            if(data.code == 200){
                window.location.href = login;
            }else {
                $("#myModalBody").text(data.msg);
                $("#myModal").prop("hidden", "");
                setTimeout(function () {
                    $("#myModal").prop("hidden", "hidden");
                }, 1000);
            }
        }
    })
}

/* 二、房源信息收藏、预约  等相关操作 */
/* 详情页面的收藏房子 */
function markHouse() {
    var houseId = $("#houseId").val();
    $.ajax({
        type:"POST",
        url: contextPath + "/mark/userMark",
        async:false,
        data:{"houseId": houseId},
        success:function (data) {
            if(data.code == 400){
                $("#myModalBody").text(data.msg);
                $("#myModal").prop("hidden", "");
                setTimeout(function () {
                    $("#myModal").prop("hidden", "hidden");
                    window.location.href = login;
                }, 1000);
            }else if(data.code == 600) {
                $("#houseMarkBtn").text("已收藏");
            }else if(data.code == 700){
                $("#houseMarkBtn").text("收藏");
            }
        }
    })
}
/* 首页的收藏房子 */
function submitMark(houseId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/mark/userMark",
        async:false,
        data:{"houseId": houseId},
        success:function (data) {
            // 收藏成功局部更新 收藏 -> 已收藏 或 已收藏 -> 收藏
            if(data.code == 400){
                window.location.href = login;
            }else if(data.code == 600) {
                $("#markStatus" + houseId).text("已收藏");
                $("#markHouseStatus" + houseId).text("已收藏");
            }else if(data.code == 700){
                $("#markStatus" + houseId).text("收藏");
                $("#markHouseStatus" + houseId).text("收藏");
            }
        }
    })
}
/* 预约房子 */
function createOrder() {
    var houseId = $("#houseId").val();
    $.ajax({
        type:"POST",
        url: contextPath + "/order/createOrder",
        async:false,
        data:{"houseId":houseId, "startDate":$("#startDate").val(), "endDate":$("#endDate").val()},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else if(data.code == 200){     // 操作成功转到签订合同页面
                    window.location.href = contextPath + "/order/orderInfo?orderId=" + data.orderId;
                }
            }, 1000);
        }
    })
}

/* 三、订单相关操作，agreement.html、order-list.html中调用 */
/* 点击调出打印（生成PDF文件） */
function printHtml(div) {
    var before = "<html><head><meta http-equiv='Content-Type' content='text/html;charset=utf-8'></head><body>";
    var print = document.getElementById(div).innerHTML;
    var result = before + print + "</body></html>";
    console.log(result);
    var wind = window.open("", 'newwindow', 'height=300, width=700, top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no');
    wind.document.body.innerHTML = result;
    wind.print();
    return false;
}
/* 签约操作 */
function confirmAgreement() {
    var orderId = $("#orderId").val();
    $.ajax({
        type:"POST",
        url: contextPath + "/order/agreementOrder",
        async:false,
        data:{"orderId":orderId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}
/* 取消订单 */
function cancelOrder(orderId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/order/cancelOrder",
        async:false,
        data:{"orderId":orderId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}
/* 申请退款*/
function applyDrawback(orderId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/order/applyDrawbackOrder",
        async:false,
        data:{"orderId":orderId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}
/* 同意退租申请 */
function drawback(orderId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/order/drawback",
        async:false,
        data:{"orderId":orderId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}
/* 不同意退租 */
function drawbackFail(orderId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/order/drawbackFail",
        async:false,
        data:{"orderId":orderId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}

/* 四、帖子相关操作，discuss.html、discuss-detail.html中调用 */
/* 发帖 */
function addDiscussPost() {
    var title = $("#recipient-name").val().trim();
    var content = $("#message-text").val().trim();
    if(title == null || title == '' || content == null || content == ''){
        $("#hintBody").text("标题或内容不能为空");
        $("#hintModal").modal("show");
        setTimeout(function(){
            $("#hintModal").modal("hide");
        }, 1000);
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/discuss/addDiscussPost",
        async:false,
        data:{"title":title, "content":content},
        success:function (data) {
            if(data.code == 400){
                window.location.href = login;
            }else {
                $("#hintBody").text(data.msg);
                $("#hintModal").modal("show");
                setTimeout(function(){
                    $("#hintModal").modal("hide");
                    window.location.href = contextPath + "/discuss/discussList";
                }, 1000);
            }
        }
    })
}
/* 管理员删除帖子 */
function deleteDiscussPost(discussPostId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/discuss/deleteDiscussPost",
        async:false,
        data:{"discussPostId":discussPostId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.href = contextPath + "/discuss/discussList";
                }
            }, 1000);
        }
    })
}
/* 管理员置顶帖子或取消置顶 */
function topDiscussPost(discussPostId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/discuss/top",
        async:false,
        data:{"discussPostId":discussPostId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else if(data.code == 200){
                    if(data.postType == 1){
                        $("#topBtn").text("取消置顶");
                    }else if(data.postType == 0){
                        $("#topBtn").text("置顶");
                    }
                }
            }, 1000);
        }
    })
}
/* 管理员加精帖子与取消加精 */
function creamDiscussPost(discussPostId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/discuss/cream",
        async:false,
        data:{"discussPostId":discussPostId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else if(data.code == 200){
                    if(data.postStatus == 1){
                        $("#creamBtn").text("取消加精");
                    }else if(data.postStatus == 0){
                        $("#creamBtn").text("加精");
                    }
                }
            }, 1000);
        }
    })
}
/* 点赞 */
function like(btn, entityId, entityType) {
    $.ajax({
        type:"POST",
        url: contextPath + "/discuss/like",
        async:false,
        data:{"entityId":entityId, "entityType":entityType},
        success:function (data) {
            if(data.code == 400){
                window.location.href = login;
            }else {
                $(btn).children("i").text(data.likeCount);
                $(btn).children("b").text(data.likeStatus == 1 ? '已赞':'赞');
            }
        }
    })
}

/* 五、反馈相关操作，feedback.html、feedback-list.html中使用 */
/* 提交评分信息 */
function putScoreInfo() {
    var orderId = $("#orderId").val();
    var environment =  $("#environment-score").val();
    var convenience = $("#convenience-score").val();
    var feel = $("#feel-score").val();
    var recommend = $("#recommend-score").val();
    if(environment == '' || convenience == '' || feel == '' || recommend == ''){
        $("#myModalBody").text("请将评分信息填写完整");
        $("#myModal").prop("hidden", "");
        setTimeout(function () {
            $("#myModal").prop("hidden", "hidden");
        }, 1000);
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/feedback/submitScoreInfo",
        async:false,
        data:{"orderId":orderId, "environment":environment, "convenience":convenience, "feel":feel, "recommend":recommend},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}
/* 提交反馈信息 */
function putFeedbackInfo() {
    $.ajax({
        type:"POST",
        url: contextPath + "/feedback/submit",
        async:false,
        data:$("#feedbackForm").serialize(),
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.href = contextPath + "/feedback/feedbackList";
                }
            }, 1000);
        }
    })
}
/* 给回复modal的隐藏框中赋值为当前列的反馈信息的id，便于后端取用 */
function showReplyModal(feedbackId) {
    $("#feedbackId").val(feedbackId);
}

/* 六、新闻相关操作，news-add.html、new-list.html中使用 */
/* 发布房源信息 */
function publishNews() {
    // 标题、内容、摘要不能为空
    var title = $("#title").val();
    var summary = $("#summary").val();
    var content = $("#content").val();
    if(title == null || summary == null || content == null || title == '' || summary == '' || content == ''){
        $("#myModalBody").text("请填写完整信息");
        $("#myModal").prop("hidden", "");
        setTimeout(function () {
            $("#myModal").prop("hidden", "hidden");
        }, 1000);
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/news/publishNews",
        async:false,
        data:$("#newsForm").serialize(),
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.href = contextPath + "/news/newsList";
                }
            }, 1000);
        }
    })
}
/* 删除新闻 */
function deleteNews(newsId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/news/deleteNews",
        async:false,
        data:{"newsId":newsId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{
                    window.location.reload();
                }
            }, 1000);
        }
    })
}

/* 六、修改密码，password-update.html中使用 */
/* 登录用户修改自己的密码 */
function submitPassword() {
    var oldPassword = $("#oldPassword").val().trim();
    var newPassword = $("#newPassword").val().trim();
    var confirmPassword = $("#confirmPassword").val().trim();
    if(oldPassword == '' || newPassword == '' || oldPassword == null || newPassword == null){
        $("#myModalBody").text("密码不能为空");
        $("#myModal").prop("hidden", "");
        setTimeout(function () {
            $("#myModal").prop("hidden", "hidden");
        }, 1000);
        return;
    }
    if(oldPassword == newPassword){
        $("#myModalBody").text("新密码不能和原密码相同");
        $("#myModal").prop("hidden", "");
        setTimeout(function () {
            $("#myModal").prop("hidden", "hidden");
        }, 1000);
        return;
    }
    if(newPassword != confirmPassword){
        $("#myModalBody").text("输入的确认密码不一致");
        $("#myModal").prop("hidden", "");
        setTimeout(function () {
            $("#myModal").prop("hidden", "hidden");
        }, 1000);
        return;
    }
    $.ajax({
        type:"POST",
        url: contextPath + "/user/updatePassword",
        async:false,
        data:{"oldPassword": oldPassword, "newPassword": newPassword},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400 || data.code == 200){
                    window.location.replace(contextPath + "/myLogout?path=/login");
                }
            }, 1000);
        }
    })
}

/* 七、模拟支付，pay.html中使用 */
function payOrder() {
    var orderId = $("#orderId").val();
    $.ajax({
        type:"POST",
        url: contextPath + "/order/payOrder",
        async:false,
        data:{"orderId":orderId},
        success:function (data) {
            $("#myModalBody").text(data.msg);
            $("#myModal").prop("hidden", "");
            setTimeout(function () {
                $("#myModal").prop("hidden", "hidden");
                if(data.code == 400){
                    window.location.href = login;
                }else{     // 转到签订合同页面
                    window.location.href = contextPath + "/index";
                }
            }, 1000);
        }
    })
}

/* 八、用户管理，user-list.html中使用 */
/* 修改用户状态 */
function changeUserStatus(userId) {
    $.ajax({
        type:"POST",
        url: contextPath + "/manager/changeUserStatus",
        async:false,
        data:{"userId":userId},
        success:function (data) {
            if(data.code == 200){
                var info = $("#userStatus" + userId).text();
                if(info == '禁用'){
                    $("#userStatus" + userId).attr("class", "text-success");
                    $("#userStatus" + userId).html("启用");
                }else if(info == '启用'){
                    $("#userStatus" + userId).attr("class", "text-danger");
                    $("#userStatus" + userId).html("禁用");
                }
            }else {
                $("#myModalBody").text(data.msg);
                $("#myModal").prop("hidden", "");
                setTimeout(function () {
                    $("#myModal").prop("hidden", "hidden");
                    if(data.code == 400){
                        window.location.href = login;
                    }
                }, 1000);
            }
        }
    })
}